package com.uidt.project.ptsj.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uidt.common.constant.Constants;
import com.uidt.common.utils.DateUtils;
import com.uidt.common.utils.SecurityUtils;
import com.uidt.common.utils.StringUtils;
import com.uidt.common.utils.uuid.UUID;
import com.uidt.framework.aspectj.lang.annotation.DataScope;
import com.uidt.framework.security.LoginUser;
import com.uidt.framework.web.domain.AjaxResult;
import com.uidt.project.ptsj.domain.*;
import com.uidt.project.ptsj.mapper.HouseInfoMapper;
import com.uidt.project.ptsj.mapper.PtsjRzrInfoMapper;
import com.uidt.project.ptsj.obj.EventForSearch;
import com.uidt.project.ptsj.service.IPtsjEventLogService;
import com.uidt.project.ptsj.service.IPtsjFileService;
import com.uidt.project.system.domain.SysDept;
import com.uidt.project.system.domain.SysRole;
import com.uidt.project.system.domain.SysUser;
import com.uidt.project.system.mapper.SysDeptMapper;
import com.uidt.project.system.service.ISysDeptService;
import org.apache.poi.ss.formula.functions.Even;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uidt.project.ptsj.mapper.EventInfoMapper;
import com.uidt.project.ptsj.service.IEventInfoService;

import javax.annotation.PostConstruct;

/**
 * 事件信息Service业务层处理
 *
 * @author uidt
 * @date 2024-08-13
 */
@Service
public class EventInfoServiceImpl extends ServiceImpl<EventInfoMapper, EventInfo> implements IEventInfoService
{
    @Autowired
    private EventInfoMapper ptsjEventInfoMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IPtsjFileService ptsjFileService;

    @Autowired
    private IPtsjEventLogService ptsjEventLogService;

    @Autowired
    private PtsjRzrInfoMapper ptsjRzrInfoMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private HouseInfoMapper houseInfoMapper;

    /**
     * 查询事件信息
     *
     * @param id 事件信息主键
     * @return 事件信息
     */
    @Override
    public EventInfo selectEventInfoById(Long id)
    {
        EventInfo eventInfo = ptsjEventInfoMapper.selectEventInfoById(id);

        if(eventInfo!=null){
            // 获取相关附件信息列表
            PtsjFile ptsjFile = new PtsjFile();
            ptsjFile.setGlid(eventInfo.getId().toString());
            ptsjFile.setTablename("ptsj_event_info");
            List<PtsjFile> fileList = ptsjFileService.selectPtsjFileList(ptsjFile);
            eventInfo.setFileList(fileList);

            // 获取相关操作记录
            PtsjEventLog eventLog = new PtsjEventLog();
            eventLog.setGlid(eventInfo.getId().toString());
            List<PtsjEventLog> ptsjEventLogs = ptsjEventLogService.selectPtsjEventLogList(eventLog);
            eventInfo.setEventLogList(ptsjEventLogs);
        }
        return eventInfo;
    }

    /**
     * 查询事件信息列表
     *
     * @param ptsjEventInfo 事件信息
     * @return 事件信息
     */
    @DataScope(deptAlias = "d")
    @Override
    public List<EventInfo> selectEventInfoList(EventForSearch ptsjEventInfo)
    {
        LoginUser user = SecurityUtils.getLoginUser();
        String deptName = user.getUser().getDept().getDeptName();
        QueryWrapper<EventInfo> queryWrapper = new QueryWrapper<>();

        if(StringUtils.isNotEmpty(ptsjEventInfo.getSearchType())){
            if("按发起".equals(ptsjEventInfo.getSearchType())){
                ptsjEventInfo.setCreatedDeptCode(user.getUser().getDept().getDeptcode());
            }else if("按接收".equals(ptsjEventInfo.getSearchType())){
                ptsjEventInfo.setProcDeptCode(user.getUser().getDept().getDeptcode());
            }
        }
        if(StringUtils.isNotEmpty(ptsjEventInfo.getPlaceName())){
            ptsjEventInfo.setPlaceName(ptsjEventInfo.getPlaceName());
        }

//        if(StringUtils.isNotEmpty(ptsjEventInfo.getProcDept())){
//            queryWrapper.eq("proc_dept",ptsjEventInfo.getProcDept());
//        }
        if(StringUtils.isNotEmpty(ptsjEventInfo.getProcMethed())){
            ptsjEventInfo.setProcMethed(ptsjEventInfo.getProcMethed());
        }
        // 自定义datascope，根据用户角色的自定义数据权限，拼接查询sql
        if(user!=null){
            StringBuilder sqlDeptcode = sysDeptService.getDeptAuthByCodeForEvent(user.getUser());
            if(sqlDeptcode!=null){
                StringBuilder dataScope = new StringBuilder();
                dataScope.append("(").append("proc_dept_code like '").append(sqlDeptcode).append("'");
                dataScope.append(" or created_dept_code like '").append(sqlDeptcode).append("')");

                Map<String,Object> paramMap = new HashMap<>();
                paramMap.put("MydataScope","("+dataScope.toString()+")");
                ptsjEventInfo.setParams(paramMap);
            }
        }
//        ptsjEventInfoMapper.selectEventInfoList(ptsjEventInfo);
        return ptsjEventInfoMapper.selectEventInfoList(ptsjEventInfo);
    }

    /**
     * app游客查询事件信息列表
     *
     * @param ptsjEventInfo 事件信息
     * @return 事件信息
     */
    @Override
    public List<EventInfo> selectEventInfoListForApp(EventInfo ptsjEventInfo)
    {
        LoginUser user = SecurityUtils.getLoginUser();
        ptsjEventInfo.setCreatedBy(user.getUserId().toString());
        return ptsjEventInfoMapper.selectEventInfoList(ptsjEventInfo);
    }

    /**
     * 新增事件信息，只是游客和业主app添加用，以及监管用户在管理后台添加用，巡检记录时候产生的事件，不在此处处理
     *
     * @param ptsjEventInfo 事件信息
     * @return 结果
     */
    @Override
    public AjaxResult insertEventInfo(EventInfo ptsjEventInfo)
    {
        LoginUser user = null;

        user = SecurityUtils.getLoginUser();

        // 当前房源信息
        HouseInfo houseInfo = houseInfoMapper.selectHouseInfoByHouseCode(ptsjEventInfo.getRoomNum());

        /*游客和业主登录，添加事件的时候，默认根据场所管辖单位来获取协会单位信息，
         *如果是监管单位，那就根据用户来获取*/
        SysDept xhDept;

        if("游客".equals(user.getUser().getDept().getDeptName())||"业主".equals(user.getUser().getDept().getDeptName())){
            if(houseInfo.getGxdwdm().equals("330999080000") ||houseInfo.getGxdwdm().equals("330999620000") ){
                /*330999080000	朱家尖派出所 330999620000	普陀山风景名胜区派出所的房源，直接找对应派出所的协会单位*/
                xhDept = sysDeptService.getXhDept(houseInfo.getGxdwdm());
            }else {
                /*除此以外派出所的房源，直接找对应区县的协会单位*/
                xhDept = sysDeptService.getXhDept(houseInfo.getGxdwdm().substring(0,6));
            }

            if("游客".equals(user.getUser().getDept().getDeptName())){
                // 游客登录之后，想要提交意见，需要先判断游客是否在改场所有入住记录
                PtsjRzrInfo rzrInfo = new PtsjRzrInfo();
                rzrInfo.setZksjhm(user.getUsername());
                rzrInfo.setFydjbh(ptsjEventInfo.getRoomNum());
                List<PtsjRzrInfo> rzrInfoList = ptsjRzrInfoMapper.selectRzrListBySjhmAndHouseCode(rzrInfo);
                if(rzrInfoList==null || rzrInfoList.size()==0){
                    return AjaxResult.error("没有您的入住记录，无法提交。");
                }
                ptsjEventInfo.setEventSource("旅客投诉");

            }else if("业主".equals(user.getUser().getDept().getDeptName())){
                ptsjEventInfo.setEventSource("房东申诉");
            }

        } else{
            // 非业主和游客的用户，添加事件的时候，默认处理单位是本级单位中的协会
            xhDept = sysDeptService.getXhDept(user.getUser().getDept().getDeptcode().split("-")[0]);
        }
        String eventId = Constants.EVENT_PREFIX+DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSSSSS);
        ptsjEventInfo.setEventId(eventId);
        ptsjEventInfo.setCreatedTime(new Date());
        ptsjEventInfo.setStatus("1");
        ptsjEventInfo.setProcDept(xhDept.getDeptName());
        ptsjEventInfo.setProcDeptCode(xhDept.getDeptcode());
        ptsjEventInfo.setFeedbackUnit(user.getUser().getDept().getDeptName());
        ptsjEventInfo.setCreatedDeptCode(user.getUser().getDept().getDeptcode());
        ptsjEventInfo.setCreatedBy(user.getUserId().toString());

        int count = ptsjEventInfoMapper.insertEventInfo(ptsjEventInfo);
        Long glid =ptsjEventInfo.getId();
        if(glid!=0 && ptsjEventInfo.getFileList()!=null){
            for(PtsjFile ptsjFile:ptsjEventInfo.getFileList()){
                ptsjFile.setTablename("ptsj_event_info");
                ptsjFile.setGlid(String.valueOf(glid));
                    ptsjFileService.insertPtsjFile(ptsjFile);
            }
        }
        return AjaxResult.success("提交成功");
    }

    /**
     * 用户不登录直接新增事件信息
     *
     * @param ptsjEventInfo 事件信息
     * @return 结果
     */
    @Override
    public int insertEventInfoNoLogin(EventInfo ptsjEventInfo)
    {
        String eventId = Constants.EVENT_PREFIX+DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);

        ptsjEventInfo.setEventId(eventId);
        ptsjEventInfo.setProcDept("协会");
        ptsjEventInfo.setEventSource("旅客投诉");
        ptsjEventInfo.setCreatedTime(new Date());
        ptsjEventInfo.setStatus("1");

        int count = ptsjEventInfoMapper.insertEventInfo(ptsjEventInfo);
        Long glid =ptsjEventInfo.getId();
        if(glid!=0 && ptsjEventInfo.getFileList()!=null){
            for(PtsjFile ptsjFile:ptsjEventInfo.getFileList()){
                ptsjFile.setTablename("ptsj_event_info");
                ptsjFile.setGlid(String.valueOf(glid));
                ptsjFileService.insertPtsjFile(ptsjFile);
            }
        }
        return count;
    }


    /**
     * 修改事件信息
     *
     * @param ptsjEventInfo 事件信息
     * @return 结果
     */
    @Override
    public int updateEventInfo(EventInfo ptsjEventInfo)
    {
        ptsjEventInfo.setUpdateTime(DateUtils.getNowDate());
        return ptsjEventInfoMapper.updateEventInfo(ptsjEventInfo);
    }

    /**
     * 批量删除事件信息
     *
     * @param ids 需要删除的事件信息主键
     * @return 结果
     */
    @Override
    public int deleteEventInfoByIds(Long[] ids)
    {
        return ptsjEventInfoMapper.deleteEventInfoByIds(ids);
    }

    /**
     * 删除事件信息信息
     *
     * @param id 事件信息主键
     * @return 结果
     */
    @Override
    public int deleteEventInfoById(Long id)
    {
        return ptsjEventInfoMapper.deleteEventInfoById(id);
    }

    /**
     * 事件处理
     *
     * @param eventLog 事件信息主键
     * @return 结果
     */
    @Override
    public AjaxResult handleEvent(PtsjEventLog eventLog){
        try{
            LoginUser user = SecurityUtils.getLoginUser();
            Date now = new Date();
            eventLog.setId(UUID.randomUUID().toString());
            eventLog.setCreatedBy(user.getUserId().toString());
            eventLog.setProcessTime(now);
            eventLog.setProcXm(user.getUsername());
            eventLog.setProcDept(user.getUser().getDept().getDeptName());
            eventLog.setProcDeptCode(user.getUser().getDept().getDeptcode());
            eventLog.setCreatedTime(now);

            // 获取事件主表信息
            EventInfo eventInfo = ptsjEventInfoMapper.selectEventInfoById(Long.parseLong(eventLog.getGlid()));
            if("转送".equals(eventLog.getProcMethed())){
                eventInfo.setProcDept(eventLog.getJsdwmc());
                eventInfo.setProcDeptCode(eventLog.getJsdwdm());
                eventInfo.setStatus("2");
            }else if("退回".equals(eventLog.getProcMethed())){

                // 获取当前用户的同级单位的协会部门
                SysDept xhdept = sysDeptService.getXhDept(user.getUser().getDept().getDeptcode().substring(0,12));
                eventInfo.setProcDeptCode(xhdept.getDeptcode());
                eventInfo.setProcDept(xhdept.getDeptName());
                eventInfo.setStatus("3");

                //事件日志添加接收单位
                eventLog.setJsdwdm(xhdept.getDeptcode());
                eventLog.setJsdwmc(xhdept.getDeptName());
            } else{
                // 受理告知（其他法定途径）、直接答复（含简易办理）都属于处理完毕
                eventInfo.setStatus("0");
                eventInfo.setProcDept(user.getUser().getDept().getDeptName());
                eventInfo.setProcessTime(now);
                eventInfo.setProcMethed(eventLog.getProcMethed());
                eventInfo.setProcOpinions(eventLog.getProcOpinions());
            }
            int count = ptsjEventInfoMapper.updateEventInfo(eventInfo);

            // 处理日志添加
            if(count!=0){
                ptsjEventLogService.insertPtsjEventLog(eventLog);
            }
        }catch (Exception e){
            return AjaxResult.error("操作失败");
        }
        return AjaxResult.success("操作成功");
    }


}
